package com.rmd.ai.demo.handler;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.ByteString;
import com.rmd.ai.grpc.service.Ability;
import com.rmd.ai.grpc.service.RecordAiOfflineServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AbilityGrpcHandler {
    private ManagedChannel channel;
    private RecordAiOfflineServiceGrpc.RecordAiOfflineServiceFutureStub offlineStub;
    @Value("${grpc.client.ability.server}")
    private String aiServer;
    @PostConstruct
    public void init () {
        String[] ips = aiServer.split(":");
        channel = ManagedChannelBuilder.forAddress(ips[0], Integer.parseInt(ips[1]))
                .usePlaintext()
                .build();//池化处理 成本高
        offlineStub = RecordAiOfflineServiceGrpc.newFutureStub(channel);

    }

    public void shutdown() {
        try {
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("",e);
        }
    }


    public void asrSpk(String audioPath, Integer fs, ByteString audioData, boolean itn, String hotwords ,List<Ability.RmdCorrectionWord> correctionWordList) {

        Ability.RecordAsrRequest request = Ability.RecordAsrRequest.newBuilder().setAudioPath(audioPath).setItn(itn).setHotwords(hotwords).addAllCorrectionWords(correctionWordList).build();
        try {
            ListenableFuture<Ability.RecordAsrResponse> future = offlineStub.asrSpk(request);
            // 注册回调
            Futures.addCallback(future, new FutureCallback<Ability.RecordAsrResponse>() {
                @Override
                public void onSuccess(Ability.RecordAsrResponse response) {
                    System.out.println("Received response: " + response.getResult());
                }

                @Override
                public void onFailure(Throwable t) {
                    t.printStackTrace();
                }
            }, Executors.newSingleThreadExecutor());
        }catch (Exception e){
            log.error("asr ",e);
        }
    }

}
